import java.net.*;
import java.io.*;
import java.util.*;

public class Server {
    public static void main(String[] args) throws Exception {

    if (args.length != 1) {
        System.err.println("Parametro: <porta>");
        System.exit(1);
    }

        int portNumber = Integer.parseInt(args[0]);
        boolean listening = true;
        Thread t;
        ArrayList<P2PFile> files = new ArrayList<P2PFile>();
        ArrayList<P2PClient> clients = new ArrayList<P2PClient>();
        List<Thread> threads = new ArrayList<Thread>();
        int running = 0;
        int c = 1;

        try (ServerSocket serverSocket = new ServerSocket(portNumber)) { 
            while (listening) {
              t = new ServerThread(serverSocket.accept(), files, clients, c);
              t.setName("Client "+c);
              t.start();
              threads.add(t);
              c++;
              running = 0;
              for (Thread th : threads) {
                if (th.isAlive()) {
                  running++;
                }
              }
              System.out.println("We have " + running + " running threads. ");
            }
      } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}